# -*- coding: utf-8 -*-
import StringIO
import base64

import qrcode


# path = os.path.dirname(__file__)
# icon_path = os.path.abspath(os.path.join(path, "avatar.png"))
# ICON_OBJ = Image.open(icon_path)


# def make_qr(url_text):
#     qr = qrcode.QRCode(
#         version=2,
#         error_correction=qrcode.constants.ERROR_CORRECT_Q,
#         box_size=10,
#         border=1
#     )
#     qr.add_data(url_text)
#     qr.make(fit=True)
#     img = qr.make_image()
#
#     img = img.convert("RGBA")
#     img_w, img_h = img.size
#     factor = 4
#     size_w = int(img_w / factor)
#     size_h = int(img_h / factor)
#
#     icon = ICON_OBJ
#     icon_w, icon_h = icon.size
#     if icon_w > size_w:
#         icon_w = size_w
#     if icon_h > size_h:
#         icon_h = size_h
#     icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)
#
#     w = int((img_w - icon_w) / 2)
#     h = int((img_h - icon_h) / 2)
#     img.paste(icon, (w, h), icon)
#     # img.save("qrcode.png")
#     return img


def make_code(text):
    qr = qrcode.QRCode(
        version=5,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=8,
        border=4
    )
    qr.add_data(text)
    qr.make(fit=True)
    img = qr.make_image()
    img_buffer = StringIO.StringIO()
    img.save(img_buffer, 'png')
    res = img_buffer.getvalue()
    img_buffer.close()
    return base64.b64encode(res)


if __name__ == "__main__":
    print make_code(
        u'alipays://platformapi/startapp?appId=09999988&actionType=toCard&sourceId=bill&cardNo=6236683150001625525&bankAccount=杨木娇&money=1.0&amount=1.0&bankMark=CCB&bankName=建设银行')
